import moment from '@/utils/moment'
// import accounting from 'accounting'

/**
 * 写入 params 参数
 * @param params 参数对象
 */
export function setUrlParams(url, params) {
	return (url + '?' + Object.keys(params).map(key => key + '=' + params[key]).join('&'))
}



/**
 * 创建选择器查询
 * @param {String} name
 */
export function createSelectorQuery(that, name) {
	return new Promise(function(resolve, reject) {
		const query = uni.createSelectorQuery().in(that)
		let nodesRef = query.select(name)
		nodesRef.fields({
			id: true,
			rect: true
		}, rek => {
			resolve(rek)
		}).exec(() => {
			reject()
		})
	})
}



/**
 * 获取缩略图
 * @param url
 * @param m 
 * 			lfit：等比缩放，限制在指定w与h的矩形内的最大图片。
 * 			mfit：等比缩放，延伸出指定w与h的矩形框外的最小图片。
 * 			fill：固定宽高，将延伸出指定w与h的矩形框外的最小图片进行居中裁剪。
 * 			pad：固定宽高，缩略填充。
 * 			fixed：固定宽高，强制缩略。
 * @param w 指定目标缩略图的宽度。
 * @param h 指定目标缩略图的高度。
 * @param l 指定目标缩略图的最长边。
 * @param s 指定目标缩略图的最短边。
 * @param limit 指定当目标缩略图大于原图时是否处理。值是 1 表示不处理；值是 0 表示处理。
 * @param color 当缩放模式选择为 pad（缩略填充）
 */
export function getThumbnail(url = '', param) {
	const prefix = '?x-oss-process=image/resize,'
	const suffix = Object.keys(param).map(key => {
		return key + '_' + param[key]
	}).join(',')
	const resize = prefix + suffix
	return url + resize
}





/**
 * 获取商品详情
 * @param html 商品详情
 */
export function getRichText(html) {
	if (!html) {
		return ''
	}
	let content = html.replace(/<img[^>]*>/gi, function(match) {
		let imgStyle = 'width: 100% !important;height: auto;'
		if (match.indexOf('style="') >= 0) {
			return match.replace(new RegExp("(i?)(\<img.*?style=['\"])([^\>]+\>)", "gmi"), "$2" + imgStyle +
				"$3");
		} else {
			return match.replace(new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)", "gmi"),
				"$2 style=\"" + imgStyle + "\"$3");
		}
	})
	return content
}




/*
 * moment 插件封装
 */

/**
 * 时间戳 => 时间(秒级时间戳)
 */
export function parseTime(time, format = 'YYYY-MM-DD HH:mm:ss') {
	return moment.unix(Number(time)).format(format)
}





/**
 * 格式化金额
 * @param {Number} number 金额
 */
export function formatMoney(number) {
	return myFormatMoney(number, '￥')
}

function myFormatMoney(number, symbol, precision, thousand, decimal, format) {
	// Resursively format arrays:
	if (isArray(number)) {
		return map(number, function(val) {
			return formatMoney(val, symbol, precision, thousand, decimal, format);
		});
	}

	// Clean up number:
	number = unformat(number);

	// Build options object from second param (if object) or all params, extending defaults:
	var opts = defaults(
			(isObject(symbol) ? symbol : {
				symbol: symbol,
				precision: precision,
				thousand: thousand,
				decimal: decimal,
				format: format
			}),
			lib.settings.currency
		),

		// Check format (returns object with pos, neg and zero):
		formats = checkCurrencyFormat(opts.format),

		// Choose which format to use for this value:
		useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;

	// Return with currency symbol added:
	return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts
		.precision), opts.thousand, opts.decimal));
};

function unformat(value, decimal) {
	// Recursively unformat arrays:
	if (isArray(value)) {
		return map(value, function(val) {
			return unformat(val, decimal);
		});
	}

	// Fails silently (need decent errors):
	value = value || 0;

	// Return the value as-is if it's already a number:
	if (typeof value === "number") return value;

	// Default decimal point comes from settings, but could be set to eg. "," in opts:
	decimal = decimal || lib.settings.number.decimal;

	// Build regex to strip out everything except digits, decimal point and minus sign:
	var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
		unformatted = parseFloat(
			("" + value)
			.replace(/\((.*)\)/, "-$1") // replace bracketed values with negatives
			.replace(regex, '') // strip out any cruft
			.replace(decimal, '.') // make sure decimal point is standard
		);

	// This will fail silently which may cause trouble, let's wait and see:
	return !isNaN(unformatted) ? unformatted : 0;
};

function checkCurrencyFormat(format) {
	var defaults = lib.settings.currency.format;

	// Allow function as format parameter (should return string or object):
	if (typeof format === "function") format = format();

	// Format can be a string, in which case `value` ("%v") must be present:
	if (isString(format) && format.match("%v")) {

		// Create and return positive, negative and zero formats:
		return {
			pos: format,
			neg: format.replace("-", "").replace("%v", "-%v"),
			zero: format
		};

		// If no format, or object is missing valid positive value, use defaults:
	} else if (!format || !format.pos || !format.pos.match("%v")) {

		// If defaults is a string, casts it to an object for faster checking next time:
		return (!isString(defaults)) ? defaults : lib.settings.currency.format = {
			pos: defaults,
			neg: defaults.replace("%v", "-%v"),
			zero: defaults
		};

	}
	// Otherwise, assume format was fine:
	return format;
}
